﻿using Common.Enums;
using Common.ServiceResponse.ValueObjects;
using Common.ServiceResponse.ValueObjects.Facebook;
using Common.Utils.Constants;
using Common.Utils.Extension;
using Infrastructure.Interfaces;
using Infrastructure.Web;

namespace Infrastructure.Gateways.Facebook
{
    public class FacebookGateway : IFacebookGateway
    {
        private readonly IWebRequest _webRequest;
        private readonly IJsonSerializer _jsonSerializer;
        private readonly IConfigurationManager _configurationManager;

        public FacebookGateway(IWebRequest webRequest, IJsonSerializer jsonSerializer, IConfigurationManager configurationManager)
        {
            _webRequest = webRequest;
            _jsonSerializer = jsonSerializer;
            _configurationManager = configurationManager;
        }

        public UserProfile GetUserProfile(string accessToken, string userId)
        {
            var url = string.Format(_configurationManager.GetValue(ConfigurationKey.UserProfile), userId);
            var completeUrl = string.Concat(url, accessToken);
            var jsonUserProfile = _webRequest.PerformJsonWebRequest(WebMethod.Get, completeUrl, string.Empty);
            return _jsonSerializer.Deserialize<UserProfile>(jsonUserProfile);
        }

        public byte[] GetProfilePicture(string accessToken, string userId)
        {
            var url = string.Format(_configurationManager.GetValue(ConfigurationKey.UserProfilePicture), userId);
            var completePictureUrl = string.Concat(url, accessToken);

            return _webRequest.PerformStreamWebRequest(WebMethod.Get, completePictureUrl, string.Empty).ToByteArray();
        }

        public Friends GetUserFriends(string completeFriendsUrl)
        {
            var jsonUserFriends = _webRequest.PerformJsonWebRequest(WebMethod.Get, completeFriendsUrl, string.Empty);
            var userFriendsData = _jsonSerializer.Deserialize<Friends>(jsonUserFriends);

            return userFriendsData;
        }

        public PhotoAlbums GetPhotoAlbums(string completeAlbumsUrl)
        {
            var jsonPhotoAlbums = _webRequest.PerformJsonWebRequest(WebMethod.Get, completeAlbumsUrl, string.Empty);
            var albumsData = _jsonSerializer.Deserialize<PhotoAlbums>(jsonPhotoAlbums);

            return albumsData;
        }

        public Photos GetPhotos(string completePhotosUrl)
        {
            var jsonPhotos = _webRequest.PerformJsonWebRequest(WebMethod.Get, completePhotosUrl, string.Empty);
            var photosData = _jsonSerializer.Deserialize<Photos>(jsonPhotos);

            return photosData;
        }

        public Wall GetWall(string completeWallUrl)
        {
            var jsonWall = _webRequest.PerformJsonWebRequest(WebMethod.Get, completeWallUrl, string.Empty);
            var wallData = _jsonSerializer.Deserialize<Wall>(jsonWall);

            return wallData;
        }
    }
}
